package com.mcintyret.site.web.controller.journal;

import com.mcintyret.site.journal.Journal;

import com.mcintyret.site.service.journal.JournalHelper;
import com.mcintyret.site.web.controller.journal.forms.JournalForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * User: mcintyret2
 * Date: 06/04/2012
 */

@Controller
public class JournalController extends BaseJournalController {

    @Resource
    private JournalHelper journalHelper;

    @RequestMapping(value = "/{origin}/add-journal", method = RequestMethod.POST)
    private String addJournalToJournalFamily(
            @PathVariable String origin,
            @Valid JournalForm journalForm,
            BindingResult bindingResult) {

        String redirectUrl = "redirect:/" + origin;

        if (!bindingResult.hasErrors()) {
            Integer id = journalHelper.addNewJournalToJournalFamily(journalForm);
            redirectUrl += "#journal_" + id;
        }
        return redirectUrl;
    }

    @RequestMapping("/{origin}/delete-journal")
    private String deleteJournal(
            @RequestParam("id") int journalId,
            @PathVariable String origin) {

        journalHelper.deleteJournalWithId(journalId);

        return "redirect:/" + origin;
    }

    @RequestMapping("/journal")
    private void getJournalPage(@RequestParam("id") int id, Model model) {
        setupCommonElements(model);
        Journal journal = journalHelper.getJournalById(id);
        model.addAttribute("journal", journal);
        model.addAttribute("origin", "journal");
    }

}
